package com.dongdong.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.dongdong.mapper.TbUserMapper;
import com.dongdong.model.TbUser;
import com.dongdong.model.TbUserExample;
import com.dongdong.service.UserService;
import com.dongdong.utils.JwtUtil;
import com.dongdong.utils.Result;
import com.dongdong.utils.ResultEnum;
import com.dongdong.utils.ShiroUtils;
import com.dongdong.vo.UserLoginVO;
import com.dongdong.vo.UserVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private TbUserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JwtUtil jwtUtil;


    @Override
    public Result register(UserVO user) {
        TbUserExample example = new TbUserExample();
        if (!StrUtil.isEmpty(user.getUsername())){

            example.createCriteria().andUsernameEqualTo(user.getUsername());
        }

        List<TbUser> tbUsers = userMapper.selectByExample(example);
        if (tbUsers != null && tbUsers.size() >=1){
            return Result.DATA(ResultEnum.USERNAME_EXIST);
        }


        String redisCode = redisTemplate.opsForValue().get("donhdongshop:sms"+user.getPhone(), 0, -1);
        if (!Objects.equals(user.getCode(),redisCode)){
            return Result.DATA(ResultEnum.CODE_ERROR);
        }
        String salt = ShiroUtils.generateSalt(8);
        String password = ShiroUtils.encryptPassword("md5", user.getPassword(), salt, 7);
        user.setPassword(password);
        user.setSalt(salt);
        user.setCreated(new Date());
        user.setUpdated(new Date());
        user.setStatus("Y");
        TbUser tbUser = new TbUser();
        BeanUtils.copyProperties(user,tbUser);

        userMapper.insertSelective(tbUser);
        return Result.OK();
    }

    @Override
    public Result login(String username, String password) {
        if (StrUtil.isEmpty(username)||StrUtil.isEmpty(password)){
            return Result.DATA(ResultEnum.NULL);
        }

        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken upToken = new UsernamePasswordToken(username, password);
        try {
            subject.login(upToken);
        } catch (UnknownAccountException e) {
            return Result.DATA(ResultEnum.ERROR);
        }catch (IncorrectCredentialsException e){
            return Result.DATA(ResultEnum.ERROR);
        }

        TbUser user = (TbUser) subject.getPrincipal();
//        脱敏
        UserLoginVO vo = new UserLoginVO();
        BeanUtils.copyProperties(user,vo);

        String token = jwtUtil.createJwt(vo.getId() + "", JSONObject.toJSONString(vo), "userRole");


        return Result.DATA(ResultEnum.LOGIN_SUCCESS).setData(token);
    }

    @Override
    public TbUser getUserByName(String username) {
        TbUserExample example = new TbUserExample();
        if (!StrUtil.isEmpty(username)){
            example.createCriteria().andUsernameEqualTo(username);
        }

        List<TbUser> tbUsers = userMapper.selectByExample(example);
        return (tbUsers!=null&&tbUsers.size()>0)?tbUsers.get(0):null;
    }
}
